using System.Collections.Generic;
using DG.Tweening;
using IQIGame.Onigao.Framework;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    /// <summary>
    /// 代码实现的UI闪烁效果
    /// </summary>
    public class CodeBasedBlinkEffectGenerator : Singleton<CodeBasedBlinkEffectGenerator>
    {
        private CodeBasedBlinkEffectGenerator()
        {
            _effects = new Dictionary<CanvasGroup, Sequence>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="target">目标CanvasGroup</param>
        /// <param name="semiCycleTime">半个循环时长</param>
        /// <param name="maxAlpha">最高Alpha值</param>
        /// <param name="minAlpha">最低Alpha值</param>
        public void Generate(CanvasGroup target, float semiCycleTime, float maxAlpha, float minAlpha)
        {
            if (_effects.TryGetValue(target, out var effect))
            {
                return;
            }

            effect = GenerateBlinkEffect(target, semiCycleTime, maxAlpha, minAlpha);
            effect.Play();
            _effects.Add(target, effect);
        }

        public void Destroy(CanvasGroup target)
        {
            if (!_effects.Remove(target, out var effect))
            {
                return;
            }

            effect.Kill();
            target.alpha = 1f;
        }

        private static Sequence GenerateBlinkEffect(CanvasGroup canvasGroup, float semiCycleTime, float max, float min)
        {
            var startTime = Time.realtimeSinceStartup;
            var speed = (max - min) / semiCycleTime;
            return DOTween.Sequence().SetTarget(canvasGroup).OnUpdate(() =>
            {
                var timePassed = Time.realtimeSinceStartup - startTime;
                var semiCycleCount = (int) (timePassed / semiCycleTime);
                var curSemiCycleTime = timePassed - semiCycleCount * semiCycleTime;
                if (semiCycleCount % 2 == 0)
                {
                    canvasGroup.alpha = Mathf.Clamp(max - curSemiCycleTime * speed, min, max);
                }
                else
                {
                    canvasGroup.alpha = Mathf.Clamp(min + curSemiCycleTime * speed, min, max);
                }
            }).SetLoops(-1);
        }

        private Dictionary<CanvasGroup, Sequence> _effects;
    }
}